<template>
  <div class="login-container">
    <div class="login-form">
      <div class="login-header">
        <h2>数据字典管理系统</h2>
        <p>欢迎登录</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form-content"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loginLoading"
            @click="handleLogin"
            class="login-btn"
          >
            {{ loginLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <div class="login-footer">
          <el-button type="text" @click="showRegister = true">
            没有账号？立即注册
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegister"
      title="用户注册"
      width="400px"
      :before-close="handleRegisterClose"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button
          type="primary"
          :loading="registerLoading"
          @click="handleRegister"
        >
          注册
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { login, register } from '@/api/auth'
import TokenUtils from '@/utils/token-utils'
import PasswordUtils from '@/utils/password-utils' 

const router = useRouter()

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

const loginFormRef = ref()
const loginLoading = ref(false)

// 注册相关
const showRegister = ref(false)
const registerFormRef = ref()
const registerLoading = ref(false)
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 登录验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少 8 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback()
          return
        }
        const hasUpperCase = /[A-Z]/.test(value)
        const hasLowerCase = /[a-z]/.test(value)
        const hasNumbers = /\d/.test(value)
        const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)
        
        if (!hasUpperCase) {
          callback(new Error('密码必须包含大写字母'))
        } else if (!hasLowerCase) {
          callback(new Error('密码必须包含小写字母'))
        } else if (!hasNumbers) {
          callback(new Error('密码必须包含数字'))
        } else if (!hasSpecialChar) {
          callback(new Error('密码必须包含特殊字符'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录方法
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loginLoading.value = true

    // 前端密码加密
    const hashedPassword = await PasswordUtils.hashPassword(loginForm.password)
    
    const response = await login({
      username: loginForm.username,
      password: hashedPassword,
      isHashed: true
    })
    
    // 使用加密存储 Token（传递用户名）
    await TokenUtils.setToken(response.token, loginForm.username)
    
    // 检查加密状态
    const status = TokenUtils.getEncryptionStatus();
    console.log('加密状态:', status);
    
    ElMessage.success('登录成功')
    router.push('/dict/type')
    
  } catch (error) {
    if (error.response?.status !== 401) {
      ElMessage.error(error.response?.data?.message || '登录失败')
    }
  } finally {
    loginLoading.value = false
  }
}

// 注册方法 使用加密密码和密码强度验证
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    
    // 前端密码强度验证
    if (!PasswordUtils.validatePasswordStrength(registerForm.password)) {
      ElMessage.error('密码必须包含大小写字母、数字和特殊字符，且长度至少8位')
      return
    }
    
    registerLoading.value = true

    // 前端密码加密
    const hashedPassword = await PasswordUtils.hashPassword(registerForm.password)
    
    // 调试信息
    console.log('注册请求:', {
      username: registerForm.username,
      originalPassword: registerForm.password,
      hashedPassword: hashedPassword,
      hashedLength: hashedPassword.length
    })

    const response = await register({
      username: registerForm.username,
      password: hashedPassword, // 发送加密后的密码
      isHashed: true //告诉后端这是前端哈希过的密码
    })

    ElMessage.success('注册成功')
    showRegister.value = false
    
    // 清空注册表单
    registerForm.username = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    
    // 自动填充登录表单
    loginForm.username = response.user?.username || registerForm.username
    
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  } finally {
    registerLoading.value = false
  }
}

// 注册对话框关闭
const handleRegisterClose = (done) => {
  registerFormRef.value?.resetFields()
  done()
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form {
  width: 400px;
  background: white;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 10px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-form-content {
  margin-top: 20px;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}
</style>